package com.wise.service.portal.content.region;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wise.entities.content.Region;
import com.wise.entities.content.RegionStatus;
import com.wise.framework.basic.EnumUtil;
import com.wise.framework.consts.Consts;
import com.wise.framework.daomodel.DaoOne4Column;
import com.wise.model.content.consts.RegionConsts;
import com.wise.summer.v1.local.content.cache.GetRegionByKeyFromCache;
import com.wise.summer.v1.local.content.cache.SetRegion2Cache;
import com.wise.summer.v1.portal.content.region.GetRegionByCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.summerframework.model.SummerService;
import org.summerframework.model.SummerServiceBean;

import static com.wise.entities.content.Region._code;
import static com.wise.framework.validation.Precondition.checkState;
import static com.wise.model.content.ContentErrMsgs.Err_000300030002;
import static com.wise.model.content.ContentErrMsgs.Err_000300030011;
import static com.wise.model.content.ContentErrMsgs.Err_000300030016;

@Slf4j
@SummerService
@Service
public class GetRegionByCodeService implements SummerServiceBean<GetRegionByCode> {

    @Override
    public void sum(GetRegionByCode summer) {
        //判断code是否为null
        checkState(StringUtils.isNotBlank(summer.getCode()), Err_000300030002);

        String key = Consts.REDIS_PREFIX + RegionConsts.DICT_REGION_CODE + summer.getCode();
        //去redis中取
        Region region = JSONObject.parseObject(GetRegionByKeyFromCache.s(key), Region.class);
        //若没有则从数据库读取
        if (region == null) {
            region = DaoOne4Column.s(Region.class, _code, summer.getCode(), Err_000300030011);
            checkState(EnumUtil.is(region.getStatus(), RegionStatus.NORMAL.value()), Err_000300030016);
            //放入redis
            String jsonString = JSON.toJSONString(region);
            SetRegion2Cache.s(key, jsonString);
        }

        summer.setSummerResult(region);
    }
}
